﻿using MeetingRoomBooking.Application.Common.Interfaces;

namespace MeetingRoomBooking.Application.Users.Commands;
public class LoginCommand : IRequest<LoginViewModel>
{
    public required string Email { get; set; }
    public required string Password { get; set; }   
}

public class LoginCommandHander : IRequestHandler<LoginCommand, LoginViewModel>
{
    private readonly IApplicationDbContext _context;
    private readonly IJwtService _jwtService;

    public LoginCommandHander(IApplicationDbContext context, IJwtService jwtService)
    {
        _context = context;
        _jwtService = jwtService;
    }

    public async Task<LoginViewModel> Handle(LoginCommand request, CancellationToken cancellationToken)
    {
        var user = await _context.Users.FirstOrDefaultAsync(x => x.Email == request.Email && x.Password == request.Password, cancellationToken: cancellationToken);

        if (user == null) throw new UnauthorizedAccessException("Email or Password invalid.");

        var token = _jwtService.GenerateToken(user);

        var userViewModel = new LoginViewModel
        {
            Email = user.Email,
            UserName = user.UserName,
            Role = user.Role,
            Token=token,
            UserId=user.Id,
        };

        return userViewModel;
    }
}
